package com.tdzh.maimaiti.view;

import android.app.Fragment;
import android.content.Context;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.*;
import android.text.format.DateUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.tdzh.maimaiti.R;
import com.tdzh.maimaiti.bean.RequestContent;
import com.tdzh.maimaiti.biz.GetContractList;
import com.tdzh.maimaiti.biz.GetLocalRequest;
import com.tdzh.maimaiti.biz.GetNative;
import com.tdzh.maimaiti.util.JSONBuilder;
import com.tdzh.maimaiti.util.UriAPI;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link HomeFragment.OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link HomeFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class HomeFragment extends BaseFragment {

    private PullToRefreshListView pullToRefresh;
    private List<Map<String, String>> data;
    private HomeAdapter mAdapter;

    private OnFragmentInteractionListener mListener;

    public HomeFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_home, container, false);
        pullToRefresh = (PullToRefreshListView) view.findViewById(R.id.left_drawer);

        data = new ArrayList<>();

        data = GetLocalRequest.getInfo(getContext(), "requestList", "requests");
        mAdapter = new HomeAdapter(getActivity().getLayoutInflater(),data);


        pullToRefresh.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() {
            @Override
            public void onRefresh(PullToRefreshBase<ListView> refreshView) {
                String label = DateUtils.formatDateTime(getActivity().getApplicationContext(), System.currentTimeMillis(),
                        DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_ALL);

               System.out.print("label " + label);

                // Update the LastUpdatedLabel
                refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);

                // Do work to refresh the list here.
                new GetDataTask().execute();
            }
        });



        // 这两个绑定方法用其一
        // 方法一
        pullToRefresh.setAdapter(mAdapter);
        pullToRefresh.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Bundle bundle = new Bundle();
                bundle.putString("fNum", "H");
                bundle.putInt("itemPos", position);
                bundle.putSerializable("requestItem", RequestContent.ITEMS.get(position) );
                mListener.onFragmentInteraction(bundle, view);
            }
        });
        return view;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    private class GetDataTask extends AsyncTask{

        @Override
        protected Object doInBackground(Object[] params) {

               // Thread.sleep(1000);
            String result = "";

            //请求数据
            HttpPost httpRequest = new HttpPost(UriAPI.HTTPGetQuestions);
            try {
                //创建参数
                byte[] data = new byte[2048];

                List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();
                    nameValuePair.add(new BasicNameValuePair("userPhone", "13269338058"));

               // System.out.println("向服务器获取问题-已启动 " + new GetNative(getActivity()).getNativePhoneNumber());
                //对提交数据进行编码
                httpRequest.setEntity(new UrlEncodedFormEntity(nameValuePair
                        , HTTP.UTF_8));
                HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequest);
                //获取响应服务器的数据
                System.out.println("连接 " + httpResponse.getStatusLine().getStatusCode());
                if (httpResponse.getStatusLine().getStatusCode() == 200) {

                    //先把从服务端来的数据转化成字节数组
                    data = EntityUtils.toByteArray((HttpEntity) httpResponse.getEntity());
                    //再创建字节数组输入流对象
                    ByteArrayInputStream bais = new ByteArrayInputStream(data);
                    //绑定字节流和数据包装流
                    DataInputStream dis = new DataInputStream(bais);
                    //将字节数组中的数据还原成原来的各种数据类型，代码如下：
                    result = new String(dis.readUTF());
                    //inStream.close();
                    System.out.println("result " + result);
                }
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
           // return result;
         /*   Map<String, String> map = new HashMap<String, String>();
            map.put("title", "新数据");
            map.put("brief", "新数据");
            map.put("author", "新数据");*/

            return result;
        }

        @Override
        protected void onPostExecute(Object o) {
           // super.onPostExecute(o);
            //Map<String, String> map = (Map<String, String>) o;
            //data.addAll()
            data = JSONBuilder.resolveJSONArray(o.toString());
            GetLocalRequest.saveInfo(getContext(), data, "requestList", "requests");
            mAdapter.notifyDataSetChanged();
            pullToRefresh.onRefreshComplete();
        }
    }

}
